
#include "Logger.h"

#include <windows.h>
#include "Common/Strings.h"

using namespace std;
using namespace ttg;
using namespace ttg::services;

//--------------
//--- Logger ---
//--------------

Logger *Logger::ref = NULL;

void Logger::startUnSafe(vector<Service *> &deps, const char *params)
{
	settings = LoggerSettings::deSerialize(params);
	output = NULL;
	if (settings.getLogFile() != NULL)
	{ fopen_s(&output, settings.getLogFile(), "w"); }
}

void Logger::stopUnSafe()
{
	if (output != NULL)
	{
		fclose(output);
		output = NULL;
	}
}

Logger::Logger()
	:Service("Logger", NULL, false)
{
	output = NULL;
	makeRegistration();
}

void Logger::printToConsole(const char *message)
{ printf("%s\n", message); }

void Logger::printToFile(const char *message)
{
	if (output != NULL)
		fprintf(output, "%s\n", message);
	else
		printToConsole(message);
}

void Logger::showMessageBox(const char *message)
{ MessageBoxA(NULL, message, "ttgLib message", MB_OK); }

void Logger::createLogRecord(LoggerSettings::MessageFilter filter, const char *message)
{
	switch (settings.getAction(filter))
	{
		case LoggerSettings::PrintToConsole:
			printToConsole(message); break;
		case LoggerSettings::PrintToFile:
			printToFile(message); break;
		case LoggerSettings::ShowMessageBox:
			showMessageBox(message); break;
		default:
			break;
	}
}

void Logger::addMessage(const char *object,
						const char *method,
						const char *description)
{
	//Creating string.
	std::string message;
	message.append(object);
	message.append(".");
	message.append(method);
	message.append("(): ");			//note: this is not a smile
	message.append(description);
	//Printing.
	createLogRecord(LoggerSettings::UserMessages, message.c_str());
}

void Logger::addError(Error &error)
{
	//Preparing message.
	std::string message;
	switch (error.getLevel())
	{
		case Error::WARNING: message.append("Warning: "); break;
		case Error::LOCAL: message.append("Error: "); break;
		case Error::FATAL: message.append("Fatal Error: "); break;
	}
	if (!error.object.empty())
	{
		message.append(error.object.c_str());
		message.append(".");
	}
	if (!error.method.empty())
	{
		message.append(error.method.c_str());
		message.append("(): ");
	}
	message.append(error.description.c_str());
	//Printing.
	createLogRecord(LoggerSettings::Errors, message.c_str());
}

void Logger::addError(const char *description)
{
	createLogRecord(LoggerSettings::Errors, description);
}

Logger::~Logger()
{
	stop();
}